package file

import (
	"entry_task/backend/src/utils"
	"entry_task/backend/src/vo"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Upload(c *gin.Context) {
	//获取文件头
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusOK, vo.FailParamError())
		return
	}
	//获取文件名
	fileName := file.Filename
	fmt.Println("文件名：", fileName)
	//保存文件到服务器本地
	//SaveUploadedFile(文件头，保存路径)
	uuidName := utils.GetUUIDName(fileName)
	filePath := utils.GetFilePath(uuidName)
	fileUrl := utils.GetFileUrl(uuidName)
	if err := c.SaveUploadedFile(file, filePath); err != nil {
		c.JSON(http.StatusOK, vo.Fail(302, "保存失败"))
		return
	}
	c.JSON(http.StatusOK, vo.Success(fileUrl))
}

func Download(c *gin.Context) {
	c.Writer.Header().Add("Content-Type", "application/octet-stream")
	fileName := c.Query("fileName")
	c.File(utils.GetFilePath(fileName))
}
